const {emptyData} = require("../utils/misc")
const ObjectId = require('mongodb').ObjectId
const router = require('koa-router')();
const mongo = require('../compents/mongo')
const {postLogData} =require("../utils/misc")
router.prefix('/classroom')

router.get('/list', async ctx => {
    postLogData("请求教室")
    let { page,name,number} = ctx.query
    let where ={name,number}
    number?"":delete where.number
    name?"":delete where.name
    const res = await mongo.find('classroom', {page:page*1,where})
    const total = res.length
    if (res) {
        ctx.body = { data: res, code: 20000, total, message: "数据请求成功" }
    } else {
        ctx.body = {data:res, code: 50001, message: "数据请求失败" }
    }
})

router.post('/save', async ctx => {
    postLogData("新增教室")
    let camData = ctx.request.body
    camData= emptyData(camData,["number","campus","name","address"])
    const res = await mongo.insertOne('classroom', { ...camData})
    if (res.insertedId) {
        ctx.body = { data: res, code: 20000, message: "数据插入成功" };
    } else {
        ctx.body = { data: res, code: 50002, message: "数据插入失败" };
    }
})
// 修改数据库
router.post('/change', async ctx => {
    postLogData("修改教室")
    const { _id } = ctx.request.body
    const update = ctx.request.body
    delete update._id
    const res = await mongo.updateOne('classroom', { where: { _id: ObjectId(_id) }, update })
    if (res.modifiedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据修改成功" };
    } else {
        ctx.body = { data: res, code: 50004, message: "数据修改失败" };
    }
})

// 删除单挑数据
router.get('/delOne', async ctx => {
    postLogData("单删教室")
    const { _id } = ctx.query
    const res = await mongo.deleteOne('classroom', { _id: ObjectId(_id) })
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据删除成功" };
    } else {
        ctx.body = { data: res, code: 50005, message: "数据删除失败" };
    }
})
// 删除多条数据  
router.get('/delMany', async ctx => {
    postLogData("多删教室")
    let { ids } = ctx.query
    ids = JSON.parse(ids)
    console.log(ids);
    const res = await mongo.deleteMany('classroom', ids)
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据批量删除成功" };
    } else {
        ctx.body = { data: res, code: 50006, message: "数据批量删除失败" };
    }
})

module.exports = router 